use std::thread;
use std::sync::{Arc, Mutex};
use std::sync::mpsc;
use std::time::Duration;

fn main() {
    println!("=== Rust多线程编程示例 ===");

    // 1. 基本的线程创建和等待
    println!("\n1. 基本线程示例");
    let handle = thread::spawn(|| {
        for i in 1..=3 {
            println!("子线程计数: {}", i);
            thread::sleep(Duration::from_millis(500));
        }
    });
    
    // 主线程同时执行
    for i in 1..=3 {
        println!("主线程计数: {}", i);
        thread::sleep(Duration::from_millis(300));
    }
    
    // 等待子线程完成
    handle.join().unwrap();

    // 2. 线程间的消息传递（使用通道）
    println!("\n2. 线程间通信示例");
    let (tx, rx) = mpsc::channel();
    let tx1 = tx.clone(); // 克隆发送者

    // 发送线程1
    thread::spawn(move || {
        let messages = vec!["你好", "世界", "!"];
        for msg in messages {
            tx1.send(msg).unwrap();
            thread::sleep(Duration::from_millis(200));
        }
    });

    // 发送线程2
    thread::spawn(move || {
        let messages = vec!["Hello", "World", "!"];
        for msg in messages {
            tx.send(msg).unwrap();
            thread::sleep(Duration::from_millis(200));
        }
    });

    // 接收消息
    for _ in 0..6 {
        println!("收到消息: {}", rx.recv().unwrap());
    }

    // 3. 共享状态（使用互斥锁Mutex）
    println!("\n3. 共享状态示例");
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..3 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();
            *num += 1;
            println!("线程增加计数器值到: {}", *num);
        });
        handles.push(handle);
    }

    // 等待所有线程完成
    for handle in handles {
        handle.join().unwrap();
    }

    // 4. 简单的线程池实现
    println!("\n4. 简单线程池示例");
    let (tx, rx) = mpsc::channel();
    let rx = Arc::new(Mutex::new(rx));
    let mut workers = vec![];

    // 创建4个工作线程
    for id in 0..4 {
        let rx = Arc::clone(&rx);
        workers.push(thread::spawn(move || {
            loop {
                let job = rx.lock().unwrap().recv();
                match job {
                    Ok(n) => {
                        println!("工作线程 {} 处理任务: {}", id, n);
                        thread::sleep(Duration::from_millis(500));
                    }
                    Err(_) => break,
                }
            }
        }));
    }

    // 发送任务
    for task in 1..=8 {
        tx.send(task).unwrap();
    }
    drop(tx); // 关闭通道

    // 等待所有工作线程完成
    for worker in workers {
        worker.join().unwrap();
    }

    println!("\n所有示例执行完成！");
}